﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using Maticsoft.DBUtility;

public partial class UserControl_PageingControl : System.Web.UI.UserControl
{
    GridView AllGv ; //定义全局变量GridView1
    SqlDataSource AllSds;//定义全局变量SqlDataSource1
    protected int totalRecordNum = 0;
    private DbHelper db = new DbHelper();
    protected void Page_Load(object sender, EventArgs e)
    {
        AllGv = (GridView)(((System.Web.UI.Page)(System.Web.HttpContext.Current.Handler)).FindControl(GV.Text)); //获取父页面的控件并附值GridView1
        //AllSds = (SqlDataSource)(((System.Web.UI.Page)(System.Web.HttpContext.Current.Handler)).FindControl(DS.Text));//获取父页面的控件并附值SqlDataSource1
        //if (AllGv == null || AllSds == null) return;
        //UPDATE by xuyongbo 2008-5-21
        if (AllGv == null || string.IsNullOrEmpty(lblSelectStr.Text))
        {     
            return;
        }

        lblWarn.Visible = false;  //提示 不显示
        ToVis.Visible = true;   //分页导航显示 

        if (!IsPostBack)
        {
            ////设置每页记录行数
            int pageSize;
            if (!int.TryParse(SysSettings.GetPageSize(), out pageSize))
                pageSize = 20;
            txtRowinOnePage.Text = pageSize.ToString();
            DBbind(this.lblCpi.Text); //绑定数据源 如何不调2次？
        }
        //AllGv.AllowPaging = true;
       

        if (int.Parse(this.lblCpi.Text) > int.Parse(this.lblallPage.Text))
            this.lblCpi.Text = this.lblallPage.Text;
        if (!IsPostBack)
        {
            this.JumpPage.Text = this.lblCpi.Text;
        }

        if (lblAllRow.Text.ToString().Equals("0"))
        {
            this.lblWarn.Visible = true;
            this.ToVis.Visible = false;
        }

        //btnCallBind.Attributes.Add("onload", "SetLocation(this)");
    }
    /// <summary>
    /// 首页按钮
    /// </summary>
    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        lblCpi.Text = "1";
        DBbind(lblCpi.Text);
        this.JumpPage.Text = this.lblCpi.Text;

    }
    /// <summary>
    /// 上一页
    /// </summary>
    protected void LinkButton3_Click(object sender, EventArgs e)
    {
        if (int.Parse(lblCpi.Text) > 1)
        {
            lblCpi.Text = (int.Parse(lblCpi.Text) - 1).ToString();
            DBbind(lblCpi.Text);
            this.JumpPage.Text = this.lblCpi.Text;
        }
    }
    /// <summary>
    /// 下一页
    /// </summary>
    protected void LinkButton4_Click(object sender, EventArgs e)
    {
        if (int.Parse(lblCpi.Text) < int.Parse(lblallPage.Text))
        {
            lblCpi.Text = (int.Parse(lblCpi.Text) + 1).ToString();
            DBbind(lblCpi.Text);
            this.JumpPage.Text = this.lblCpi.Text;
        }
    }
    /// <summary>
    /// 尾页
    /// </summary>
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        lblCpi.Text = lblallPage.Text.Equals("0") ? "1" : lblallPage.Text;
        DBbind(lblCpi.Text);
        this.JumpPage.Text = this.lblCpi.Text;

        this.LbtFirstPage.Enabled = true;
        this.LbtLastPage.Enabled = false;
    }

    public DataTable SearchData(int start, int end)
    {
        string sql = lblSelectStr.Text.ToString();
        if(string.IsNullOrEmpty(sql))
            return null;
        string[] arr = sql.Split('|');
        string sqlTotal = MultiDbSql.GetTotalNumSql(arr[0], PubConstant.GetDBType());
        string sqlSel = MultiDbSql.GetDefiniteSql(arr[0], start, end, PubConstant.GetDBType(), arr[1], arr[2]);
        DataTable dtSource = null;
        try
        {
            DataTable dt = db.DataTable(sqlTotal);
            if(dt == null)
                return null;
            totalRecordNum = int.Parse(dt.Rows[0][0].ToString());
            dtSource = db.DataTable(sqlSel);

            //移去oracle 带回的rownum_列（即不显示）
            for (int i = 0; i < dtSource.Columns.Count; i++)
            {
                if (dtSource.Columns[i].ColumnName.ToUpper().Equals("ROWNUM_"))
                    dtSource.Columns.Remove(dtSource.Columns[i].ColumnName);                 
             }

        }
        catch
        {
            return dtSource;
        }

        return dtSource;
    }

    public int GetTotalRecordNum()
    {
        string sql = lblSelectStr.Text.ToString();
        if(string.IsNullOrEmpty(sql))
            return 0;
        string[] arr = sql.Split('|');
        string sqlTotal = MultiDbSql.GetTotalNumSql(arr[0], PubConstant.GetDBType());
        try
        {
            DataTable dt = db.DataTable(sqlTotal);
            if(dt == null)
                return 0;
            return int.Parse(dt.Rows[0][0].ToString());
        }
        catch
        {
            return 0;
        }
    }

    /// <summary>
    /// 绑定数据
    /// </summary>
    public void DBbind(string curNum)
    {
        if (curNum.Equals("0"))
            curNum = "1";

        LbtFirstPage.Enabled = true;
        LbtLastPage.Enabled = true;
        LbtPreviousPage.Enabled = true;
        LbtNextPage.Enabled = true;

        int curPage = int.Parse(curNum);
        if (!IsNumber(txtRowinOnePage.Text.Trim()))
        {
            Response.Write("<script>alert('不是正整数，请输入正整数！');</script>");
            return;
        }
        int pageSize = int.Parse(txtRowinOnePage.Text);
        int start = (curPage - 1) * pageSize;
        int end = curPage * pageSize;
        //totalRecordNum = GetTotalRecordNum();
        DataTable dtSource = SearchData(start, end);
        if (dtSource == null)
            return;

        AllGv.DataSource = dtSource.DefaultView;
        AllGv.DataBind();

        lblAllRow.Text = totalRecordNum.ToString();

        //算出总的页数
        if (totalRecordNum % pageSize != 0)
        {
            lblallPage.Text = (totalRecordNum / pageSize + 1).ToString();//页的总数量
        }
        else
        {
            lblallPage.Text = (totalRecordNum / pageSize).ToString();
        }

        if (this.lblallPage.Text.ToString().Equals("0"))//0页
        {
            this.lblCpi.Text = "0";
            this.LbtNextPage.Enabled = false;
            this.LbtLastPage.Enabled = false;
            this.JumpPage.Enabled = false;
        }
        else if (this.lblallPage.Text.ToString().Equals("1"))//1页
        {
            this.LbtNextPage.Enabled = false;
            this.LbtLastPage.Enabled = false;
            this.JumpPage.Enabled = false;
        }
        else //多页
        {
            this.LbtNextPage.Enabled = true;
            this.LbtLastPage.Enabled = true;
            this.JumpPage.Enabled = true;

        }
        //判断是首页 
        if (curNum.Equals("1"))
        {
            this.LbtFirstPage.Enabled = false;
            this.LbtPreviousPage.Enabled = false;
        }
        //判断是尾页
        if (lblallPage.Text.ToString().Equals(curNum))
        {
            this.LbtNextPage.Enabled = false;
            this.LbtLastPage.Enabled = false;
        }

        //AllGv.DataSourceID = DS.Text;
        if (!lblAllRow.Text.Equals("0") && curNum.Equals("1"))
        {
            this.lblCpi.Text = "1";
        }        
    }
    protected void txtRowinOnePage_TextChanged(object sender, EventArgs e)
    {
        check_txtRowinOnePage();
        DBbind(this.lblCpi.Text);
    }
    public void check_txtRowinOnePage()//检查输入每页的行数
    {
        if (txtRowinOnePage.Text.Trim().Equals("") || !IsNumber(txtRowinOnePage.Text.Trim()))
        {                                    
            txtRowinOnePage.Text = SysSettings.GetSysSetting("每页记录数");
            return;
        }
        if (int.Parse(txtRowinOnePage.Text) < 1)
            txtRowinOnePage.Text = SysSettings.GetSysSetting("每页记录数");
    }
    protected void JumpPage_TextChanged(object sender, EventArgs e)//第几页
    {
        if (this.JumpPage.Text == null || !IsNumber(this.JumpPage.Text))
        {
            Response.Write("<script>alert('不是正整数，请输入正整数！');</script>");
            return;
        }
        if (int.Parse(this.JumpPage.Text) > 0 && int.Parse(this.JumpPage.Text) <= int.Parse(this.lblallPage.Text))
        {
            DBbind(this.JumpPage.Text);
            this.lblCpi.Text = this.JumpPage.Text;
        }
    }

    protected void btnCallBind_Click(object sender, EventArgs e)
    {
        DBbind(this.lblCpi.Text);
    }
    /**
     * 判断可否转换为正整数
     * 参数：strNumber要进行判断的字符串
     * 返回：是返回true,否返回false
     * */
    public bool IsNumber(String strNumber)
    {
        Regex numberPattern = new Regex("^[0-9]+$");
        return numberPattern.IsMatch(strNumber);
    }

}

